package com.wn.class30.cotroller.houtai;

import com.wn.class30.entity.*;
import com.wn.class30.mapper.CuponDao;
import com.wn.class30.service.*;
import com.wn.class30.tools.Page;
import com.wn.class30.tools.Result;
import com.wn.class30.tools.StringToArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: OrderController 方法是
 * @author: jzy
 * @date: 2020/4/2 4:13 PM
 */
@RestController
@RequestMapping("houtai/page/order")
@Slf4j
public class OrderController {
    @Resource
    private AllOrderService allOrderService;
    @Resource
    private OrderService orderService;
    @Resource
    private BackUserService backUserService;
    @Resource
    private UserAddressService userAddressService;
    @Resource
    private Couponservice couponservice;
    @Resource
    private BusinessService businessService;
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private BackProductService backProductService;
    @Resource
    private CommentService commentService;
    //用于记录订单是否已经发货，第一次发货减少库存，第二次发货只更改物流信息
//    private Map<Integer,Integer> isSendProduct = new HashMap<>();

    /**
     * 根据条件分页查询订单信息
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequiresPermissions("/houtai/page/order/list")
    @RequestMapping("/houtai/page/order/orderlist")
    public Result getOrderlist(){
        return new Result("0","success",null,null);
    }
    @RequestMapping("list")
    public Result selectOrders(Integer page, Integer limit,String myorderId, String myorderNumber, String username,String orderStatus,String startDate,String endDate)throws Exception{
        log.info("myorderNumber======="+myorderNumber);
        log.info("username========"+username);
        log.info("orderStatus=========="+orderStatus);
        log.info("startDate=========="+startDate);
        log.info("endDate=========="+endDate);
        Map<String,String> map = new HashMap<>();
        map.put("page",String.valueOf((page-1)*limit) );
        map.put("limit",String.valueOf(limit) );
        map.put("myorderNumber", myorderNumber);
        map.put("username", username);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("orderStatus",orderStatus);
        map.put("myorderId",myorderId);
        log.info("这是map中的myorderNumber==========="+map.get("myorderNumber"));
        //判断登陆用户是否为管理员，如果是管理员可以查询所有订单，非管理员只能查询对应商铺订单
        Subject subject = SecurityUtils.getSubject();
        AdminUser adminUser = (AdminUser) subject.getPrincipal();
        if(adminUser.getBusinessId() != 0){
            map.put("businessId",adminUser.getBusinessId()+"");
        }
        Long orderCount = orderService.getOrderCount(map);
        Page p = new Page();
        p.setCurrentPage((page-1)*limit);
        p.setTotalSize(orderCount);
        p.setPageSize(limit);
        long pageSize = orderCount % limit == 0? orderCount / limit:orderCount / limit + 1;
        p.setPageSize((int)pageSize);
        List<Myorder> orders = orderService.selectOrders(map);
        for (Myorder order : orders) {
            order.setUser(backUserService.selectUserByUserId(order.getUserId()));
            order.setBusiness(businessService.selectBusinessById(order.getBussinessId()));
        }
        return new Result("0","success",p,orders);
    }


    /**
     * 批量删除或者单个删除订单
     * @param oid
     * @return
     * @throws Exception
     */
    @RequestMapping("delete")
    @RequiresPermissions("/houtai/page/order/delete")
    public Result deleteOrderByOid(String oid)throws Exception{
        log.info("oid=================="+oid);
        if(oid != null && !"".equals(oid)){
            Integer[] intOids = StringToArray.getArray(oid);
            for (Integer intOid : intOids) {
                orderService.deleteOrderByOid(intOid);
            }
            return new Result("200","success",null,null);
        }
        return new Result("500","error",null,null);
    }

    /**
     * 查询单个订单，用于显示订单详情
     * @param myOrderId
     * @return
     * @throws Exception
     */
    @RequestMapping("selectById")
    @RequiresPermissions("/houtai/page/order/list")
    public Result selectMyOrderById(Integer myOrderId)throws Exception{
        Myorder order = orderService.selectMyOrderById(myOrderId);
        order.setUser(backUserService.selectUserByUserId(order.getUserId()));
        order.setBusiness(businessService.selectBusinessById(order.getBussinessId()));
        List<MyorderDetail> myorderDetails = orderDetailService.selectOrderDetailsByMyOrderId(order.getMyorderId());
        for (MyorderDetail myorderDetail : myorderDetails) {
            myorderDetail.setProduct(backProductService.selectProductById(myorderDetail.getProductId()));
            myorderDetail.setComment(commentService.selectCommentById(myorderDetail.getCommentId()));
        }
        order.setMyorderDetails(myorderDetails);
        Allorder allorder = allOrderService.selectAllOrderById(order.getAllorderId());
        order.setUserAddress(userAddressService.selectUserAddressById(allorder.getUserAddressId()));
        allorder.setCupon(couponservice.selectCuponById(allorder.getUserCuponId()));
        order.setAllorder(allorder);
        return new Result("200","success",order,null);
    }

    /**
     * 商家发货并减少库存
     * @param myorder
     * @return
     * @throws Exception
     */
    @RequestMapping("sendProduct")
    public Result sendProduct(Myorder myorder)throws Exception{
        log.info(myorder+"");
        Myorder order = orderService.selectMyOrderById(myorder.getMyorderId());
        order.setWuliuGongshi(myorder.getWuliuGongshi());
        order.setWuliuNumber(myorder.getWuliuNumber());
        order.setMyorderStatus(2);
        //判断当前订单是否发货
//        Integer sendProductTime = isSendProduct.get(order.getMyorderId());
        //当前商品第一次发货，减少库存，同时判断商品库存是否充足
//        if (sendProductTime == null || sendProductTime < 2){
//            //更改商品库存
//            List<MyorderDetail> myorderDetails = orderDetailService.selectOrderDetailsByMyOrderId(order.getMyorderId());
//            //存放每个商品库存是否充足的标识
//            List<Boolean> isProductOk = new ArrayList<>();
//            for (MyorderDetail myorderDetail : myorderDetails) {
//                Product product = backProductService.selectProductById(myorderDetail.getProductId());
//                if(product.getProductNum() > 0 && product.getProductNum() > myorderDetail.getProductNum()){
//                    isProductOk.add(true);
//                }else{
//                    isProductOk.add(false);
//                    return new Result("600",product.getProductName()+"库存不足,请添加库存后再发货",null,null);
//                }
//            }
//            //判断所有商品的库存是否充足
//            boolean flag = true;
//            for (Boolean aBoolean : isProductOk) {
//                if (aBoolean == false){
//                    flag = false;
//                    break;
//                }
//            }
//            //所有商品库存充足时提交修改商品库存
//            if(flag){
//                for (MyorderDetail myorderDetail : myorderDetails) {
//                    Product product = backProductService.selectProductById(myorderDetail.getProductId());
//                    product.setProductNum(product.getProductNum() - myorderDetail.getProductNum());
//                    backProductService.updateProductById(product);
//                }
//                //当商品库存都减少后把当前订单设置为已发货状态
//                isSendProduct.put(order.getMyorderId(),2);
//            }
//        }
        //修改订单的物流公司和物流编号
        orderService.updateMyOrderById(order);
        return new Result("200","success",null,null);
    }
}